package com.kinyx.framework.db.vo;

import java.util.List;
import java.util.stream.Collectors;

import com.kinyx.framework.db.defines.INamingStrategy;
import com.kinyx.framework.enums.impl.ErrorCodeX;
import com.kinyx.framework.exception.KRuntimeException;
import com.kinyx.framework.reflect.KFieldUtils;
import com.kinyx.framework.utils.KListUtils;

import lombok.Getter;
import lombok.ToString;

/**
 * 映射信息
 */
@Getter
@ToString(exclude = {
		"columnInfos", "mappingClass"
})
public class MappingInfo {

	/** 映射类 */
	private final Class<?> mappingClass;

	/** 映射表名称 */
	private String tableName;
	/** 映射表别名 */
	private String tableAlias;

	/** 映射列信息列表 */
	private List<ColumnInfo> columnInfos;

	public MappingInfo(final Class<?> mappingClass, final INamingStrategy namingStrategy) {
		this.mappingClass = mappingClass;

		this.tableName = MappingHandler.load_table_name(this.mappingClass, namingStrategy);
		this.tableAlias = MappingHandler.load_table_alias(this.mappingClass);

		this.columnInfos = KListUtils.convert(KFieldUtils.getFieldList(this.mappingClass, true, false, false)//
				.stream().filter(field -> MappingHandler.isColumn(field)).collect(Collectors.toList()), field -> {
					return new ColumnInfo(//
							field, //
							field.getName(), //
							field.getType(), //

							MappingHandler.load_column_name(field, namingStrategy) //
					);
				});
	}

	public ColumnInfo getColumnInfo(final String fieldName) {
		for (final ColumnInfo columnInfo : this.columnInfos) {
			if (columnInfo.getFieldName().equals(fieldName)) { return columnInfo; }
		}
		throw new KRuntimeException(ErrorCodeX.NotConfiged);
	}

}
